package com.fms.fmsapi.common.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fms.fmsapi.common.ResponseEnum;
import com.fms.fmsapi.entity.R;
import com.fms.fmsapi.mapper.UserMapper;
import com.fms.fmsapi.service.UserService;
import com.fms.fmsapi.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = JwtUtil.getToken(request);
        if(token.equals("-1")) return true;
        // JSON 转换对象
        ObjectMapper objectMapper = new ObjectMapper();

        //设置响应格式
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        // 如果没有accessToken信息，同样不予放行
        if (!StringUtils.hasText(token)) {
            response.getWriter().print(objectMapper.writeValueAsString(R.fail(ResponseEnum.USER_NOT_LOGIN))); //没有accessToken信息
            return false;
        }

        //验证token
        boolean res = JwtUtil.checkToken(token);
        if(res){
            String userId = JwtUtil.getUserId(token);
            /*
            * 处理逻辑，这里从简，啥也不处理
            * */
            if(userMapper.selectById(userId)!=null) return true;
            return  true;//请求放行
        } else{
            // 拦截请求并返回错误信息
            response.getWriter().print(objectMapper.writeValueAsString(R.fail(ResponseEnum.INVALID_TOKEN))); //accessToken无效
            return false;
        }
    }
}
